var webview = document.getElementById('webview');
var USERKEY = Math.random().toString(36).substr(2);
var timeid = null;
var websocket = null;

webview.addEventListener("dom-ready", function () {
  webview.openDevTools();
});
$("#test-refresh").on("click", function () {
  webview.preload = "electron/console/KZT0201002-001.js";
  var current = webview.getURL();
  webview.loadURL(current)
});
$("#test-show-btn").on("click", function () {
  $("#menu").animate({left: "0"});
});
$("#menu").on("mouseleave", function () {
  $(this).animate({left: "-300px"});
});
$("#test-console").on("click", function () {
  webview.src = 'http://consoleproject-test.sxiaobao.com/pages/login/login.html';
});
$("#test-buyer").on("click", function () {
  webview.src = 'http://buyercenter-test.sxiaobao.com';
});
$("#test-seller").on("click", function () {
  webview.src = 'http://sellercenter-test.sxiaobao.com/common/login-page/login-page.html';
});
$("#test-out").on("click", function () {
  init();
});
$("#test-inside").on("click", function () {
  webview.openDevTools();
});
$("#accordion").on("click", "button", function () {
  var msg = $(this).data('name');
  if (msg) {
    var current = webview.getURL();
    if (current.indexOf("?") > 0) {
      webview.loadURL(current + "&_from=" + msg)
    } else {
      webview.loadURL(current + "?_from=" + msg)
    }
  }
});
webview.addEventListener('ipc-message', function(event) {
  websocket.send(event.channel)
});
function init() {
  //判断当前浏览器是否支持WebSocket
  if ('WebSocket' in window) {
    websocket = new WebSocket("ws://101.37.175.21:8040/automatedtest/websocket/" + USERKEY);
  }
  else {
    alert('Not support websocket')
  }

  //连接发生错误的回调方法
  websocket.onerror = function () {
    console.log("error");
  };

  //连接成功建立的回调方法
  websocket.onopen = function (event) {
    console.log('链接成功');
    timeid && window.clearInterval(timeid);
  };
  //发送消息
  /*websocket.send("");*/
  //接收到消息的回调方法
  websocket.onmessage = function (event) {
    console.log(event.data);
    var data = JSON.parse(event.data);
    var planData = data.data;
    var current = webview.getURL();
    if (current.indexOf("?") > 0) {
      webview.loadURL(current + "&_data=" + JSON.stringify(planData))
    } else {
      webview.loadURL(current + "?_data=" + JSON.stringify(planData))
    }
  };

  //连接关闭的回调方法
  websocket.onclose = function () {
    console.log("close");
    window.clearInterval(timeid);
    timeid = window.setInterval(init, 3000);
  };

  //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
  window.onbeforeunload = function () {
    websocket.close();
  }
}